package com.uuah.server.config.spring;

import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.beans.factory.parsing.Problem;
import org.w3c.dom.Element;


public class MissingParserProblemReporter extends FailFastProblemReporter {

	public static final String NO_PARSER_PREFIX = "Cannot locate BeanDefinitionParser";

	// @Override
	public void fatal(Problem problem) {
		if (isMissingParser(problem)) {
			problem = extendProblemDetails(problem);
		}
		super.fatal(problem);
	}

	protected boolean isMissingParser(Problem problem) {
		String message = problem.getMessage();
		return (null != message && message.startsWith(NO_PARSER_PREFIX));
	}

	protected Problem extendProblemDetails(Problem problem) {
		try {
			String element = ((Element) problem.getLocation().getSource())
					.getLocalName();
			String namespace = ((Element) problem.getLocation().getSource())
					.getNamespaceURI();
			String message = "The element '" + element
					+ "' does not have an associated Bean Definition Parser."
					+ "  Is the module or transport associated with "
					+ namespace + " present on the classpath?";
			return new Problem(message, problem.getLocation(), problem
					.getParseState(), problem.getRootCause());
		} catch (Exception e) {
			return problem;
		}
	}

}
